package com.finger.controller;

import com.finger.controller.utils.R;
import com.finger.dao.UserDao;
import com.finger.dao.WordDao;
import com.finger.pojo.Scale;
import com.finger.pojo.Source;
import com.finger.pojo.User;
import com.finger.service.UserService;
import com.finger.service.WordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/users")
@CrossOrigin(origins = "*",allowedHeaders = {"Content-Type", "Authorization"})
//RESTful风格控制层
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private WordService wordService;
    @Autowired
    private UserDao userDao;
    //用户注册功能
    @GetMapping("/register/{username}/{password}")
    public R register(@PathVariable String username,@PathVariable String password){
        R res = new R();

        String msg = userService.register(username, password);
        if ("注册成功".equals(msg)) {
            res.setFlag(true);
            res.setMsg(msg);
        }else if ("用户名已存在".equals(msg)) {
            res.setFlag(true);
            res.setMsg(msg);
        }else {
            res.setFlag(false);
            res.setMsg("注册失败");
        }
        return res;
    }

    //用户登录功能
    @GetMapping("/login/{username}/{password}")
    public R login(HttpServletRequest request, @PathVariable String username, @PathVariable String password) {
        //查询用户是否存在
        User user = userService.login(username, password);
        if (user != null) {
            //用户信息存在,登录放行逻辑
            HttpSession session = request.getSession();
            session.setAttribute("user",user);
            return new R(true,user,"登录成功");
        }else  {
            //用户信息不存在，登录失败
            return new R(true,"登录失败");
        }
    }

    //返回当前用户相关的数据
    @GetMapping("/userInfo/{id}")
    public R getUserInfo(@PathVariable int id) {
        Scale sacle = wordService.getSacle(id);
        if (sacle != null) {
            return new R(true,sacle,"获取成功");
        }else {
            return new R(false,null,"获取失败");
        }
    }
    //返回当前系统用户排名数据
    @GetMapping("/user_ranking")
    public R getUserRanking() {
        return new R(true,userService.getUserRanking(),"获取成功");
    }

    @PostMapping("/source")
    public R createSource(@RequestBody Source source) {
        return new R(true,userDao.createSource(source),"创建词源成功");
    }
    @PostMapping("/nowsource")
    public R updateUserNowSource(@RequestBody User user) {
        return new R(true,userDao.updateUserSource(user),"切换词源成功");
    }
}
